#!/bin/sh
set -e

case "$1" in
    purge)
        systemctl daemon-reload 2>/dev/null || true
        killall -SIGKILL -u iotedge || true

        if [ -d /etc/aziot ]; then
            rm -rf /etc/aziot/edged
            rm -f /etc/aziot/config.toml
        fi

        rm -rf /var/log/aziot

        # Remove supplementary members from the iotedge group.
        for u in $(getent group iotedge | sed -e "s/^.*://" -e "s/,/ /g"); do
            gpasswd -d "$u" iotedge
        done

        # Remove iotedge users.
        /usr/sbin/userdel iotedge
        rm -rf /var/lib/aziot/edged

        /usr/sbin/userdel edgeagentuser
        /usr/sbin/userdel edgehubuser

        if [ -d /var/lib/aziot ] && [ -z "$(ls -A /var/lib/aziot)" ]; then
            rm -rf /var/lib/aziot
        fi
    ;;
    remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
    ;;
    *)
        echo "postrm called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac


#DEBHELPER#

exit 0
